package com.game.doudizhu.service;

import com.game.doudizhu.model.GameAction;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

@Service
public class GameMessageService {
    
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    // 游戏动作消息
    public void sendGameAction(Long roomId, String type, GameAction action) {
        messagingTemplate.convertAndSend(
            getGameActionDestination(roomId),
            new GameMessage(type, action)
        );
    }
    
    // 游戏状态更新消息
    public void sendGameStateUpdate(Long roomId, Object gameState) {
        messagingTemplate.convertAndSend(
            getGameStateDestination(roomId),
            gameState
        );
    }
    
    // 错误消息
    public void sendErrorMessage(Long roomId, String type, String message, String code) {
        messagingTemplate.convertAndSend(
            getErrorDestination(roomId),
            new ErrorMessage(type, message, code)
        );
    }
    
    // 玩家特定消息
    public void sendPlayerMessage(Long roomId, Long playerId, String type, Object data) {
        messagingTemplate.convertAndSend(
            getPlayerDestination(roomId, playerId),
            new GameMessage(type, data)
        );
    }
    
    // 获取目标地址
    private String getGameActionDestination(Long roomId) {
        return String.format("/topic/game/%d/action", roomId);
    }
    
    private String getGameStateDestination(Long roomId) {
        return String.format("/topic/game/%d", roomId);
    }
    
    private String getErrorDestination(Long roomId) {
        return String.format("/topic/error/%d", roomId);
    }
    
    private String getPlayerDestination(Long roomId, Long playerId) {
        return String.format("/topic/game/%d/player/%d", roomId, playerId);
    }
    
    // 消息包装类
    @Data
    private static class GameMessage {
        private String type;
        private Object data;
        
        public GameMessage(String type, Object data) {
            this.type = type;
            this.data = data;
        }
    }
    
    @Data
    private static class ErrorMessage {
        private String type;
        private String message;
        private String code;
        
        public ErrorMessage(String type, String message, String code) {
            this.type = type;
            this.message = message;
            this.code = code;
        }
    }
} 